<?php

namespace common\observer;

use Throwable;
use support\SingletonTrait;
use common\model\EntityModel;
use common\service\CommonService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 镜头时长同步到分镜上
 */
class ShotDurationSyncToStoryboard implements SplObserver
{
    use SingletonTrait;

    /**
     * @param SplSubject $subject
     * @return void
     */
    function update(SplSubject $subject): void
    {
        $entity = $subject->getSubjectData();
        $updateData = $subject->getSplUpdateData();

        if (!isset($updateData['duration'])) {
            return;
        }
        if ($entity['module_id'] != module_by_code('shot')['id']) {
            return;
        }
        $entityJson = json_decode($entity['json'], true);
        if (!isset($entityJson['shot_storyboard'])) {
            return;
        }
        $newDuration = $updateData['duration'];
        $queryFields = [
            'id',
            'name',
            'duration',
            'project_id',
            'initial_episode_code',
            'showings_number',
        ];
        $storyboard = model(EntityModel::class)
            ->where(['id' => $entityJson['shot_storyboard'], 'module_id' => module_by_code('storyboard')['id']])
            ->field($queryFields)->find();
        if (empty($storyboard) || $storyboard['duration'] == $newDuration) {
            return;
        }


        $storyboardUpdateData = [
            'id' => $storyboard['id'],
            'duration' => $newDuration,
        ];
        try {
            request()->getModuleCode('storyboard');
            CommonService::instance('entity')->update($storyboardUpdateData, 'storyboard', false);

            $shot = model(EntityModel::class)
                ->where([
                    'initial_episode_code' => $storyboard['initial_episode_code'],
                    'showings_number' => $storyboard['showings_number'],
                    'name' => $storyboard['name'],
                    'project_id' => $storyboard['project_id'],
                    'module_id' => module_by_code('shot')['id']])
                ->field($queryFields)->find();

            if (empty($shot) || $shot['duration'] == $newDuration) {
                return;
            }
            $shotUpdateData = [
                'id' => $shot['id'],
                'duration' => $newDuration,
            ];
            request()->getModuleCode('shot');
            CommonService::instance('entity')->update($shotUpdateData, 'shot', false);

        } catch (Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }

}
